<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="parkingAreaForm" :label-width="formLabelWidth" ref="parkingAreaFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="车位号" prop="areaNumber">
              <el-input v-model="parkingAreaForm.areaNumber" placeholder="请输入车位号" maxlength="32"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="楼栋名称" prop="buildingName">
              <el-input v-model="parkingAreaForm.buildingName" placeholder="请选择楼栋名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findBuilding"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="所在楼层" prop="floorNumber">
              <el-input v-model="parkingAreaForm.floorNumber" placeholder="请输入所在楼层" maxlength="32"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单元房号" prop="residentRoomNumber">
              <el-input v-model="parkingAreaForm.residentRoomNumber" placeholder="请选择单元房号" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findRoom"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="车牌" prop="licensePlate">
              <el-input v-model="parkingAreaForm.licensePlate" placeholder="请输入车牌" maxlength="32"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-select v-model="parkingAreaForm.status" placeholder="请选择状态">
                <el-option label="临停" :value="30"></el-option>
                <el-option label="业主" :value="10"></el-option>
                <el-option label="月租" :value="20"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="buildingSelectorVisible" v-if="buildingSelectorVisible" title="楼栋信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <building-selector @building-selected-event="handleBuildingSelectedEvent">
      </building-selector>
    </el-dialog>
    <el-dialog v-model="roomSelectorVisible" v-if="roomSelectorVisible" title="单元信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <room-selector @room-selected-event="handleRoomSelectedEvent">
      </room-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import parkingAreaApi from '@/api/parkingAreaApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {ParkingAreaForm} from "@/types/req/parkingAreaForm";
import type {Result} from '@/types/result'
import type {ParkingArea} from "@/types/resp/parkingArea";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import BuildingSelector from "@/views/building/BuildingSelector.vue";
import RoomSelector from "@/views/room/RoomSelector.vue";

const props = defineProps<Id>()
const parkingAreaFormRef = ref<FormInstance | null>(null);
const parkingAreaForm = reactive<ParkingAreaForm>({
  areaNumber: '',
  buildingId: 0,
  buildingName: '',
  floorNumber: '',
  residentRoomId: 0,
  residentRoomNumber: '',
  licensePlate: '',
  status: undefined,
})
const buildingSelectorVisible = ref<boolean>(false)
const roomSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetParkingAreaAddEvent'): void;
  (e: 'closeParkingAreaAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  areaNumber: [
    { required: true, message: '请输入车位号', trigger: 'blur' }
  ],
  buildingName: [
    { required: true, message: '请输入楼栋名称', trigger: 'blur' }
  ],
  floorNumber: [
    { required: true, message: '请输入所在楼层', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请输入状态', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initParkingAreaFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initParkingAreaFormById = async (id: number) => {
  const resp: Result<ParkingArea> = await parkingAreaApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(parkingAreaForm, resp.data)
  }
}

const onReset = () => {
  if (parkingAreaFormRef.value) {
    parkingAreaFormRef.value.resetFields()
  }
  emit('resetParkingAreaAddEvent')
}

const onSave = () => {
  if (!parkingAreaFormRef.value) {
    return
  }
  parkingAreaFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await parkingAreaApi.save(parkingAreaForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeParkingAreaAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findBuilding = () => {
  buildingSelectorVisible.value = true
}

const handleBuildingSelectedEvent = (selectedBuilding: any) => {
  buildingSelectorVisible.value = false
  if (selectedBuilding && 'buildingId' in selectedBuilding && parkingAreaForm.buildingId !== selectedBuilding['buildingId']) {
    parkingAreaForm.buildingId = selectedBuilding['buildingId']
    parkingAreaForm.buildingName = selectedBuilding['buildingName']
  }
}

const findRoom = () => {
  roomSelectorVisible.value = true
}

const handleRoomSelectedEvent = (selectedRoom: any) => {
  roomSelectorVisible.value = false
  if (selectedRoom && 'residentRoomId' in selectedRoom && parkingAreaForm.residentRoomId !== selectedRoom['residentRoomId']) {
    parkingAreaForm.residentRoomId = selectedRoom['residentRoomId']
    parkingAreaForm.residentRoomNumber = selectedRoom['residentRoomNumber']
  }
}

const onBack = () => {
  emit('closeParkingAreaAddEvent')
}
</script>

<style lang="scss">
</style>
